from QQLoginTool.QQtool import OAuthQQ
from django import http
from django.conf import settings
from django.contrib.auth import login
from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View

from apps.oauth.models import OAuthQQUser
from apps.oauth.utils import SecretOauth
from meiduo_mall.settings.dev import logger
from utils.response_code import RETCODE


# 是否绑定用户ID
def is_bind_openid(request, openid):
    # 判断该QQ 用户是否 被绑定过
    try:
        authuser = OAuthQQUser.objects.get(openid=openid)
    except Exception as e:

        # 没绑定---弹出绑定个人信息的 页面
        context = {'openid': openid}
        context = {'openid': SecretOauth().dumps(context)}
        return render(request, 'oauth_callback.html', context)

    else:
        # 绑定过 就跳转到 -首页
        loginuser = authuser.user
        login(request, loginuser)

        response = redirect(reverse('contents:index'))
        response.set_cookie('username', loginuser.userame, max_age=3600 * 24 * 15)

        return response


class QQAuthUserView(View):
    def get(self, request):
        """Oauth2.0认证"""
        # 提取code请求参数
        code = request.GET.get('code')
        if not code:
            return http.HttpResponseForbidden('缺少code')

        # 创建工具对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)

        try:
            # 使用code向QQ服务器请求access_token
            access_token = oauth.get_access_token(code)

            # 使用access_token向QQ服务器请求openid
            openid = oauth.get_open_id(access_token)
        except Exception as e:
            logger.error(e)
            return http.HttpResponseServerError('OAuth2.0认证失败')

        # 是否绑定 openid
        response = is_bind_openid(request, openid)
        return response

    def post(self, request):
        mobile = request.POST.get('mobile')
        pwd = request.POST.get('password')
        sms_code_client = request.POST.get('sms_code')
        openid = SecretOauth.loads(request.POST.get('openid')).get('openid')

        if not openid:
            return render(request, 'oauth_callback.html', {'openid_errmsg': '无效的openid'})

        # 保存注册数据
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 用户不存在,新建用户
            user = User.objects.create_user(username=mobile, password=pwd, mobile=mobile)
        else:
            # 如果用户存在，检查用户密码
            if not user.check_password(pwd):
                return render(request, 'oauth_callback.html', {'account_errmsg': '用户名或密码错误'})

        # 绑定用户
        OAuthQQUser.objects.create(
            openid=openid,
            user=user
        )

        # 保持登录状态
        login(request, user)
        response = redirect(reverse('contents:index'))
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)

        return response


class QQAuthURLView(View):
    # 返回QQ的 登录网址
    def get(self, request):
        # 1.建立QQ登录
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=next)

        # 2. 生成链接
        login_url = oauth.get_qq_url()

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'login_url': login_url})
